package com.wufeng.ws;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wufeng.entity.ChatRecord;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;


//@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
@ServerEndpoint(value = "/chat")
@Component
public class ChatEndPoint {

    //存储在线的用户
    public static final Map<String, Session> onlineUsers = new java.util.concurrent.ConcurrentHashMap<>();

    /**
     * 建立WebSocket连接后被调用
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {

        //将session保存，k为name，v为session
        onlineUsers.put(session.getQueryString(), session);


        Set<Map.Entry<String, Session>> entries =
                onlineUsers.entrySet();
        for (Map.Entry<String, Session> entry : entries) {

            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        System.out.println("当前在线人数：" + onlineUsers.size());
//        try{
//            session.getBasicRemote().sendText("连接成功");//发送消息
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    /**
     * 浏览器发送消息到服务器，该方法被调用
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        //将消息推送给指定用户
        System.out.println(message);

        try {
            ChatRecord chatRecord = new ObjectMapper().readValue(message, ChatRecord.class);
            System.out.println(chatRecord);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //根据receivedid，从onlineUsers中获取session，通过session，发送消息
    }


    /**
     * 断开连接时
     *
     * @param session
     */
    @OnClose
    public void OnClose(Session session) {
        System.out.println("已断开连接");

        System.out.println(session.getQueryString());

        //从集合中移除在线对象
        onlineUsers.remove(session.getQueryString());

        System.out.println("当前在线人数：" + onlineUsers.size());


    }


}
